package com.danco.training.bookshop.service.file;

import java.io.IOException;

import org.apache.log4j.Logger;

import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import com.danco.training.bookshop.entity.Book;
import com.danco.training.bookshop.entity.storage.BookStorage;
import com.danco.training.bookshop.entity.storage.Bookshop;
import com.danco.training.bookshop.service.storage.BookStorageService;
//import com.danco.training.controller.BookController;
//import com.danco.training.view.Separator;



public class BookStorageFile {

	private BookStorageService bookStorageService = Bookshop.getBookshopInstance().getBookStorageService();
	private BookStorage bookStorage = BookStorage.getBookStorageInstance() ;
//	private TextFileWorker textFileWorker;
	//private BookController bookController = new BookController();
	private static final Logger logger = Logger.getLogger(BookStorageFile.class);

	public BookStorageFile(BookStorage bookStorage, String FILE)
			throws IOException {

		try {
		Path filePath = Paths.get(FILE);
		Files.createFile(filePath);
		this.bookStorage = bookStorage;
	//	textFileWorker = new TextFileWorker(FILE);
		}
		
		catch (FileAlreadyExistsException e){
			logger.error(e.getMessage(), e);
			Files.deleteIfExists( Paths.get(FILE));			
			Path filePath = Paths.get(FILE);
			Files.createFile(filePath);
			this.bookStorage = bookStorage;
	//		textFileWorker = new TextFileWorker(FILE);			
			
		}
		catch (Exception e){
			logger.error(e.getMessage(), e);
		}

	}

	public void saveBooksToFile() {

		try{
		String[] books = new String[bookStorage.getBooks().size()];
		for (int i = 0; i < books.length; i++) {
			//books[i] = bookController .bookDetails(bookStorage.getBooks().get(i).getId());
		}
	//	textFileWorker.writeToFile(books);
		}
		catch (Exception e){
			logger.error(e.getMessage(), e);
		}
	}

	public List<Book> readBooksFromFile() {
		
		

		List<Book> books = new ArrayList<Book>();
		
		try {
	//	String[] booksArray = textFileWorker.readFromFile();

	//	for (int i = 0; i < booksArray.length; i++) {
//			int index1 = booksArray[i].indexOf(Separator.BOOK_SEPARATOR.toString());
//			int index2 = booksArray[i].indexOf(Separator.BOOK_SEPARATOR.toString(), index1+1);
//			int index3 = booksArray[i].indexOf(Separator.BOOK_SEPARATOR.toString(), index2+1);
	//		Book b = new Book(Integer.valueOf((booksArray[i].substring(0, index1))),
				//	booksArray[i].substring(index1+1, index2),booksArray[i].substring(index2+1, index3), booksArray[i].substring(index3+1));
	//		books.add(b);
		//}


		
		}
		catch (StringIndexOutOfBoundsException e){
			logger.error(e.getMessage(), e);
		}
        catch (Exception e){
        	logger.error(e.getMessage(), e);
        	
		}
		
		return books;
		

	}

}
